package com.zzq.demo.tio.client.handler;

import com.zzq.demo.tio.common.AbsAioHandler;
import com.zzq.demo.tio.common.HelloPacket;
import com.zzq.demo.tio.common.Type;
import com.zzq.demo.tio.common.bs.AbsBsHandler;
import lombok.extern.slf4j.Slf4j;
import org.tio.client.intf.ClientAioHandler;
import org.tio.core.ChannelContext;
import org.tio.core.intf.Packet;

import java.util.HashMap;
import java.util.Map;

/**
 * @author : zhaoziqian
 * @description :
 * @date : 2019/10/24 11:04
 */
@Slf4j
public class HelloClientAioHandler extends AbsAioHandler implements ClientAioHandler {

    private static Map<Byte, AbsBsHandler<?>> handlerMap = new HashMap<>();

    static {
        handlerMap.put(Type.SIMPLE_RESP, new SimpleMsgRespHandler());
    }

    @Override
    public void handler(Packet packet, ChannelContext channelContext) throws Exception {
        HelloPacket helloPacket = (HelloPacket) packet;
        Byte type = helloPacket.getType();
        AbsBsHandler<?> bsHandler = handlerMap.get(type);
        if (bsHandler == null) {
            log.error("{}, 找不到处理类，type:{}", channelContext, type);
            return;
        }
        bsHandler.handler(helloPacket, channelContext);
    }

    private static HelloPacket heartbeatPacket = new HelloPacket(Type.HEART_BEAT_REQ, null);

    /**
     * 此方法如果返回null，框架层面则不会发心跳；如果返回非null，框架层面会定时发本方法返回的消息包
     *
     * @param channelContext
     * @return
     */
    @Override
    public Packet heartbeatPacket(ChannelContext channelContext) {
        return heartbeatPacket;
    }
}
